import { writeFile as _writeFile, readFile as _readFile } from "fs/promises";
import { resolve } from "path";

export const sleep = (time = 1000) =>
  new Promise((ok) =>
    setTimeout(() => {
      ok(true);
    }, time)
  );

export const writeFile = (p, text) => {
  return _writeFile(resolve(p), text, { encoding: "utf-8" });
};

export const readFile = (p) => {
  return _readFile(resolve(p), { encoding: "utf-8" });
};

export const searchPathToCode = (path) => {
  // in   -> '/search-_E6_B3_B0_E5_8B_92_E6_96_AF_E5_A8_81_E5_A4_AB_E7_89_B9-1.htm'
  // in   -> '/search-_E6_B3_B0_E5_8B_92_E6_96_AF_E5_A8_81_E5_A4_AB_E7_89_B9-1-2.htm'
  // out  -> '_E6_B3_B0_E5_8B_92_E6_96_AF_E5_A8_81_E5_A4_AB_E7_89_B9-1'
  const code = path.split(".")?.[0];
  const [_search, realCode, one] = code.split("-");
  return `${realCode}-${one}`;
};

export const codeToSearchPath = (code, pageNum) => {
  // in   -> '_E6_B3_B0_E5_8B_92_E6_96_AF_E5_A8_81_E5_A4_AB_E7_89_B9-1'
  // out  -> '/search-_E6_B3_B0_E5_8B_92_E6_96_AF_E5_A8_81_E5_A4_AB_E7_89_B9-1.htm'
  return `/search-${code}${pageNum ? `-${pageNum}` : ""}.htm`;
};
